package com.dnjn.happiness.system.util;

import com.dnjn.happiness.system.api.domain.SysTeam;
import com.dnjn.happiness.system.service.ISysTeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Random;

@Component
public class GenerateInviteCode {


    @Autowired
    private ISysTeamService teamService;

    /**
     * 随机获取邀请码 Invitation code
     */
    public String getInviteCode(){
        //随机数
        String ALLCHAR = "0123456789ABCDEFGHJKMNPQRSTUVWXYZ";
        // length：随机位数
        int length = 6;
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
        }
        Long count = teamService.lambdaQuery().eq(SysTeam::getInviteCode, sb.toString()).count();
        if (count <= 0){
            return sb.toString();
        }else {
            getInviteCode();
        }
        return sb.toString();
    }

    /**
     * 获取短信验证码
     * @param length
     * @return
     */
    public static String getRandomString(int length) {
        String str = "0123456789";
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(str.length());
            sb.append(str.charAt(index));
        }
        return sb.toString();
    }
}
